import React, { memo, useState, useEffect, useCallback } from 'react';
import { Modal, Checkbox, Input } from 'antd';
import { IProps, SerialNumber } from './interface';
import { warning } from './../../utils/message/message';
import Icon from './../icon/Icon';
import cls from './styles.module.scss';

const TextArea = Input.TextArea;

export default memo(({ visible, onCancel, onOk, defaultSerialNumbers, totalNumber, disabled, stockSerialNumbers }: IProps) => {

  const [checkeds, setCheckeds] = useState({});
  const [val, setVal] = useState('');

  useEffect(() => {
    if (!defaultSerialNumbers) return;
    setVal(defaultSerialNumbers.map(item => item.serialNumber).join('\n'))
  }, [defaultSerialNumbers])

  const onChangeChecked = useCallback((id: string) => {
    setCheckeds({ ...checkeds, [id]: !checkeds[id] })
  }, [checkeds]);

  const onChangeVal = useCallback((e) => setVal(e.target.value), []);

  const _onOk = useCallback(() => {
    const serialNumbers: SerialNumber[] = [];

    val.split('\n').forEach(item => {
      if (item) serialNumbers.push({ serialNumber: item.trim(), id: '' })
    })

    if (serialNumbers.length !== totalNumber) return warning(window.$app.t('serialNumberErrTip'));
    if (disabled) return onCancel();
    onOk && onOk(serialNumbers);
  }, [val]);

  const move = useCallback(() => {
    const serialNumbers: string[] = [];
    const vals = val.split('\n').reduce((next, cur: string) => (next[cur] = true) && next, {});

    (stockSerialNumbers || []).forEach(item => {
      if (checkeds[item.id as string] && !vals[item.serialNumber]) serialNumbers.push(item.serialNumber);
    })

    setVal(val + (val ? '\n' : '') + serialNumbers.join('\r\n'))
}, [checkeds, stockSerialNumbers, val]);

  return (
    <Modal onOk={_onOk} visible={visible} onCancel={onCancel} title={
     <>
    <span>{window.$app.t('serialNumberManage')}</span>
    <span className={cls.spacing}>{window.$app.t('lineTotal')} {totalNumber}</span>
    </>
    } width={784}>
      <div className={cls.box}>
        {stockSerialNumbers && stockSerialNumbers.length ? (
          <>
            <div className={cls.list}>
              {(stockSerialNumbers || []).map((item, index) => (
                <p key={item.id || index}>
                  <Checkbox disabled={disabled} onChange={() => onChangeChecked(item.id)} checked={checkeds[item.id]}>
                    {item.serialNumber}
                  </Checkbox>
                </p>
              ))}
            </div>
            <div onClick={move} className={cls.move}><Icon icon='&#xe618;' /></div>
          </>
        ) : null}
        <TextArea disabled={disabled} value={val} onChange={onChangeVal} placeholder={window.$app.t('serialNumberInputTip')} className={cls.textarea} />
      </div>
    </Modal>
  )
})